import { BaseService, CoolCommException } from '@cool-midway/core';
import { Inject, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import * as md5 from 'md5';
import { Equal, Repository } from 'typeorm';
import { v1 as uuid } from 'uuid';
import { PluginService } from '../../plugin/service/info';
import { UserInfoEntity } from '../entity/info';
import { UserRelationEntity } from '../entity/user_relation';
import { UserSmsService } from './sms';
import { UserWxService } from './wx';
import { Context } from '@midwayjs/koa';
import axios from 'axios';
import moment = require('moment');
import { Utils } from '../../../comm/utils';

/**
 * 用户信息
 */
@Provide()
export class UserInfoService extends BaseService {
  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  @InjectEntityModel(UserRelationEntity)
  userRelationEntity: Repository<UserRelationEntity>;

  @Inject()
  pluginService: PluginService;

  @Inject()
  userSmsService: UserSmsService;

  @Inject()
  userWxService: UserWxService;

  @Inject()
  ctx: Context;

  @Inject()
  utils: Utils;

   // 获取修改密码的手机验证码
  async getResetPhoneCode( ) {
    return await this.userSmsService.sendSms(17302644218);
  }
  
  /**
   * 绑定小程序手机号
   * @param userId
   * @param code
   * @param encryptedData
   * @param iv
   */
  async miniPhone(userId: number, code: any, encryptedData: any, iv: any) {
    const phone = await this.userWxService.miniPhone(code, encryptedData, iv);
    await this.userInfoEntity.update({ id: Equal(userId) }, { phone });
    return phone;
  }

  /**
   * 获取用户信息
   * @param id
   * @returns
   */
  async person(id) {
    const info = await this.userInfoEntity.findOneBy({ id: Equal(id) });
    delete info.password;
    return info;
  }

  /**
   * 注销
   * @param userId
   */
  async logoff(userId: number) {
    await this.userInfoEntity.update(
      { id: userId },
      {
        status: 2,
        phone: null,
        unionid: null,
        nickName: `已注销-00${userId}`,
        avatarUrl: null,
      }
    );
  }

  /**
   * 更新用户信息
   * @param id
   * @param param
   * @returns
   */
  async updatePerson(id, param) {
    const info = await this.person(id);
    if (!info) throw new CoolCommException('用户不存在');
    try {
      // 修改了头像要重新处理
      if (param.avatarUrl && info.avatarUrl != param.avatarUrl) {
        const file = await this.pluginService.getInstance('upload');
        param.avatarUrl = await file.downAndUpload(
          param.avatarUrl,
          uuid() + '.png'
        );
      }
    } catch (err) {}
    try {
      return await this.userInfoEntity.update({ id }, param);
    } catch (err) {
      throw new CoolCommException('更新失败，参数错误或者手机号已存在');
    }
  }

  /**
   * 更新密码
   * @param userId
   * @param password
   * @param 验证码
   */
  async updatePassword(userId, password, code) {
    const user = await this.userInfoEntity.findOneBy({ id: userId });
    const check = await this.userSmsService.checkCode(user.phone, code);
    if (!check) {
      throw new CoolCommException('验证码错误');
    }
    await this.userInfoEntity.update(user.id, { password: md5(password) });
  }

  /**
   * 绑定手机号
   * @param userId
   * @param phone
   * @param code
   */
  async bindPhone(userId, phone, code) {
    const check = await this.userSmsService.checkCode(phone, code);
    if (!check) {
      throw new CoolCommException('验证码错误');
    }
    await this.userInfoEntity.update({ id: userId }, { phone });
  }

  /* 通过手机号密码注册帐号 */
  async register(phone, password, parentId?: number) {
    let user = await this.userInfoEntity.findOneBy({ phone });
    if (user) {
      throw new CoolCommException('手机号已注册');
    }

    user = await this.userInfoEntity.save({
      phone,
      password: md5(password),
      role: 2, // 默认普通用户
      nickName: `用户${phone.slice(-4)}`,
      status: 1,
    });

    if (parentId) {
      const parentUser = await this.userInfoEntity.findOneBy({ id: parentId });
      if (!parentUser) {
        throw new CoolCommException('上级用户不存在');
      }

      const userRelation = new UserRelationEntity();
      userRelation.userId = user.id;
      userRelation.parentId = parentId;

      // 继承上级关系链
      const parentRelation = await this.userRelationEntity.findOneBy({
        userId: parentId,
      });
      if (parentRelation) {
        userRelation.level1ParentId = parentId;
        userRelation.level2ParentId = parentRelation.level1ParentId;
        userRelation.level3ParentId = parentRelation.level2ParentId;
      }

      await this.userRelationEntity.save(userRelation);
    }

    return user;
  }

  /**
   * 创建代理
   * @param phone
   * @param password
   * @param profitRatio
   * @returns
   */
  async createAgent(phone: string, password: string, profitRatio: number) {
    // 获取当前登录用户的ID
    const currentUserId = this.ctx.user?.id;

    let creatorAgentLevel = 0; // 默认为平台创建，agentLevel为0

    if (!currentUserId) {
      // 如果没有获取到当前登录用户的ID，则返回错误
      throw new CoolCommException('创建代理失败');
    }

    // 获取当前登录用户的信息
    const currentUser = await this.userInfoEntity.findOneBy({
      id: currentUserId,
    });
    if (currentUser && currentUser.role === 1) {
      // 确保当前用户是代理
      creatorAgentLevel = currentUser.agentLevel || 0;
    }

    // 计算新代理的agentLevel
    const newAgentLevel = creatorAgentLevel + 1;

    if (newAgentLevel > 3 || newAgentLevel < 1) {
      // 代理级别不能超过3级
      throw new CoolCommException('您不能创建代理');
    }

    if (profitRatio < 0 || profitRatio > 100) {
      throw new CoolCommException('分润比例必须在0-100之间');
    }

    let user = await this.userInfoEntity.findOneBy({ phone });
    if (user && user?.role !== 0) {
      throw new CoolCommException('该用户已经是代理或商户！');
    } else if (user) {
      // 如果已经注册了，并且是普通用户，则更新为代理
      user.role = 1;
      user.agentLevel = newAgentLevel; // 使用计算出的新代理级别
      user.profitRatio = profitRatio;
      user.password = md5(password);
      user.nickName = `代理${phone.slice(-4)}`;
      user.status = 1; // 激活状态
      user = await this.userInfoEntity.save(user);
    } else {
      user = await this.userInfoEntity.save({
        phone,
        password: md5(password),
        role: 1, // 代理
        agentLevel: newAgentLevel, // 使用计算出的新代理级别
        profitRatio,
        nickName: `代理${phone.slice(-4)}`,
        status: 1,
      });
    }

    if (currentUserId) {
      const userRelation = new UserRelationEntity();
      // 创建用户关系
      userRelation.userId = user.id;
      // 父节点是 当前登录用户
      userRelation.parentId = currentUserId;

      // 继承上级关系链
      const parentRelation = await this.userRelationEntity.findOneBy({
        userId: currentUserId,
      });

      // 如果当前用户是一级代理，那么其创建的代理就是二级代理
      if (currentUser?.agentLevel === 1) {
        // 二级代理 对应的 一级代理id就是当前登陆的者
        userRelation.level1ParentId = currentUserId;
        userRelation.level2ParentId = null;
        userRelation.level3ParentId = null;
      }
      // 如果当前用户是二级代理，那么其创建的代理就是三级代理
      else if (currentUser?.agentLevel === 2) {
        userRelation.level1ParentId = parentRelation?.level1ParentId;
        userRelation.level2ParentId = currentUserId;
        userRelation.level3ParentId = null;
      }

      await this.userRelationEntity.save(userRelation);
    }

    return user;
  }

  /**
   * 创建商户
   * @param phone
   * @param password
   * @param agentId
   * @returns
   */
  async createMerchant(body) {
    const { phone, password, agentId } = body;
    let user = await this.userInfoEntity.findOneBy({ phone });
    if (user && user?.role !== 0) {
      throw new CoolCommException('该用户已经是代理或商户！');
    } else if (user) {
      user.role = 2;
      user.password = md5(password);
      user.nickName = `商户${phone.slice(-4)}`;
      user.status = 1;
      user = await this.userInfoEntity.save(user);
    } else {
      user = await this.userInfoEntity.save({
        phone,
        password: md5(password),
        role: 2, // 商户
        nickName: `商户${phone.slice(-4)}`,
        status: 1,
      });
    }

    // 如果有推荐人id
    if (agentId) {
      const userRelation = new UserRelationEntity();
      // 父节点是 当前登录用户
      userRelation.parentId = agentId;

      // 获取推荐人的信息
      const agentUser = await this.userInfoEntity.findOneBy({ id: agentId });

      /* 第一级 */
      let level1ParentId = null;
      let level2ParentId = null;
      let level3ParentId = null;

      // 继承推荐人的关系链
      const parentRelation = await this.userRelationEntity.findOneBy({
        userId: agentId,
      });

      /* 判断当前推荐人的代理等级 */
      switch (agentUser?.agentLevel) {
        case 1:
          level1ParentId = agentUser?.id;
          break;
        case 2:
          level1ParentId = parentRelation?.level1ParentId;
          level2ParentId = agentUser?.id;
          break;
        case 3:
          level1ParentId = parentRelation?.level1ParentId;
          level2ParentId = parentRelation?.level2ParentId;
          level3ParentId = agentUser?.id;
          break;
        default:
          throw new CoolCommException('您不能创建商户');
      }

      // 继承三级代理关系
      userRelation.level1ParentId = level1ParentId;
      userRelation.level2ParentId = level2ParentId;
      userRelation.level3ParentId = level3ParentId;

      await this.userRelationEntity.save(userRelation);
    }

    return user;
  }

  /**
   * 获取用户下级
   * @param userId
   * @param level
   * @returns
   */
  async getChildren(userId: number, level: number) {
    let children = [];
    if (level === 1) {
      children = await this.userRelationEntity.find({
        where: { parentId: userId },
      });
    } else if (level === 2) {
      children = await this.userRelationEntity.find({
        where: { level2ParentId: userId },
      });
    } else if (level === 3) {
      children = await this.userRelationEntity.find({
        where: { level3ParentId: userId },
      });
    }
    return children;
  }

  // 获取代理列表，只能获取自己的下级代理
  async getAgentList() {
    const user = this.ctx.user;
    if (!user || !user.id) {
      return [];
    }

    //  找出userRelationEntity表中parentId等于user.id的记录
    const children = await this.userRelationEntity.find({
      where: { parentId: user.id },
    });
    // 通过children获取代理列表并返回
    return children;
  }

  async add(param: any | any[]): Promise<Object> {
    return this.userInfoEntity.insert({
      ...param,
      password: md5(param.password),
    });
  }

  // 申请合同
  async applyContract(params) {
    // 平台编号+14位年月日时（24小时制）分秒+8位的随机数（同一接入机构不重复）
    const order_no = `${moment().format('YYYYMMDDHHmmss')}${Math.floor(
      Math.random() * 100000000
    )}`;

    const _body = {
      req_data: {
        order_no: order_no,
        // 机构号，固定
        org_id: 984459,
        // 固定
        ec_type_code: 'EC008',
        // 法人/经营者证件类型
        cert_type: 'RESIDENT_ID',
        // 法人/经营者姓名
        cert_name: '陈祥龙',
        // 法人/经营者证件号码
        cert_no: '352228198411032513',
        // 签约手机号
        mobile: '17316345409',
        // 57 对公、 58 对私，这里固定
        acct_type_code: 58,
        // 企业/经营者结算卡号
        acct_no: '6228481548812211172',
        // 企业/经营者结算卡名称
        acct_name: '陈祥龙',
        // 电子合同内容参数集合
        ec_content_parameters: JSON.stringify({
          A1: '测试商户',
        }),
        // 企业/经营者结算开户行号
        openning_bank_code: '103403626011',
        //  	企业/经营者结算开户行名称
        openning_bank_name: '农业银行',
        // 	备注说明
        remark: '测试',
        version: '1.0',
        // 回调地址
        ret_url: 'https://www.baidu.com',
      },
    };

    try {
      // 调用微信接口生成二维码
      const result = await axios.post(
        'https://s2.lakala.com/api/v3/mms/open_api/ec/apply',
        _body,
        {
          headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
            Authorization: this.utils.createAuthorization(_body),
          },
        }
      );

      console.log('请求头', result?.headers);

      console.log('请求体', result?.config?.data);

      return result?.data;
    } catch (error) {
      console.log('报错', error);

      return error?.response?.data;
    }
  }

  async createAgentNew(params) {
    return this.applyContract(params);
  }

  async settle(params) {
    const order_no = `${moment().format('YYYYMMDDHHmmss')}${Math.floor(
      Math.random() * 100000000
    )}`;

    const _body = {
      // 是否法人进件
      isLegalPerson: false,
      // 固定
      userNo: 24371029,
      // 邮箱
      email: 'wmj541452385@sina.com',
      // 固定的
      busiCode: 'WECHAT_PAY',
      merRegName: '祥龙游戏室',
      // TP_MERCHANT:企业 TP_PERSONAL:⼩微个⼈
      merType: 'TP_PERSONAL',
      // 不能少于七个中文
      merName: '测试商户测试商户',
      // 去掉省，市区后的详细地址
      merAddr: '白云大道北129号',
      provinceCode: 3900,
      cityCode: 4030,
      countyCode: 4036,
      latitude: 1,
      longtude: 2,
      source: 'H5',
      businessContent: '游戏币',
      larName: '测试商户',
      larIdType: '01',
      larIdCard: '352228198411032513',
      larIdCardStart: '2023-03-07',
      larIdCardEnd: '2043-03-07',
      contactMobile: 17316345409,
      contactName: '陈祥龙',
      openningBankCode: '103403626011',
      openningBankName: '中国农业银行股份有限公司屏南县支行',
      clearingBankCode: '103100000026',
      // 结算省份代码
      settleProvinceCode: '35',
      // 结算省份名称
      settleProvinceName: '福建',
      // 结算城市代码
      settleCityCode: '4036',
      // 结算城市名称
      settleCityName: '屏南县',
      // 结算人银行卡
      accountNo: '6228481548812211172',
      // 结算人账户名称
      accountName: '陈祥龙',
      accountType: '58',
      accountIdCard: '352228198411032513',
      externalNo: 'rtewtqwet',
      // 业务拓展信息
      bizContent: {
        fees: [
          {
            feeCode: 'WECHAT',
            feeValue: 0.38,
          },
          {
            feeCode: 'ALIPAY',
            feeValue: 0.38,
          },
          {
            feeCode: 'CREDIT_CARD',
            feeValue: 0.6,
          },
          {
            feeCode: 'DEBIT_CARD',
            feeValue: 0.5,
            topFee: 20,
          },
        ],
        mcc: '5943',
        termNum: '1',
        activityId: '208',
      },
      // 附件信息结合
      attchments: [
        {
          id: 'merchant/null/20250829160730474122ID_CARD_FRONT.png',
          type: 'BANK_CARD',
        },
        {
          id: 'merchant/null/20250829160730474122ID_CARD_FRONT.png',
          type: 'OTHERS',
        },
        {
          id: 'merchant/null/20250829160730474122ID_CARD_FRONT.png',
          type: 'ID_CARD_FRONT',
        },
        {
          id: 'merchant/null/20250829160730474122ID_CARD_FRONT.png',
          type: 'ID_CARD_BEHIND',
        },
        {
          id: 'merchant/null/20250829160730474122ID_CARD_FRONT.png',
          type: 'SHOP_OUTSIDE_IMG',
        },
        {
          id: 'merchant/null/20250829160730474122ID_CARD_FRONT.png',
          type: 'SHOP_INSIDE_IMG',
        },
      ],
      // 结算类型
      settleType: 'D1',
      settlementType: 'AUTOMATIC',
      // 电子合同编号
      contractNo: '3333',
    };

    try {
      // 调用微信接口生成二维码
      const result = await axios.post(
        'https://htkactvi.lakala.com/registration/merchant',
        _body,
        {
          headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
            Authorization: `bearer 9b7da8d9-14ee-475c-923d-34917467b792`,
          },
        }
      );

      console.log('请求头', result?.headers);

      console.log('请求体', result?.config?.data);

      return result?.data;
    } catch (error) {
      console.log('报错', error);

      return error?.response?.data;
    }
  }
}
